from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from .forms import LoginForm, RefisterForm, setNameForm
from .models import UserProfile, onceName
from utils.mixin_utils import LoginRequiredMixin, get_current_ip
import json
from treehole.models import secret, comment, agree

class IndexView(View):
    def get(self, request):
        return render(request, 'index.html', {})

class LoginViews(View):
    # 秘密树洞登录
    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST.get("username", "")
            password = request.POST.get("password", "")
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return HttpResponse('{"ret": "true","status": "success", "msg": "登录成功"}', content_type='application/json')
            else:
                return HttpResponse('{"ret": "true","status": "fail", "msg": "用户名或密码错误"}', content_type='application/json')
        else:
            return HttpResponse('{"ret": "true","status": "fail", "msg": "用户名或密码格式错误"}', content_type='application/json')


class RegisterView(View):
    # 注册
    def post(self, request):
        register_form = RefisterForm(request.POST)
        if register_form.is_valid():
            username = request.POST.get('username', '')
            phone = request.POST.get('phone', '')
            if UserProfile.objects.filter(username=username):
                return HttpResponse('{"ret": "true","status": "fail", "msg": "用户名已存在"}', content_type='application/json')
            if UserProfile.objects.filter(phone=phone):
                return HttpResponse('{"ret": "true","status": "fail", "msg": "手机号已存在"}', content_type='application/json')
            password = request.POST.get('password', '')
            user_profile = UserProfile()
            user_profile.username = username
            user_profile.phone = phone
            user_profile.password = make_password(password)
            user_profile.save()
            return HttpResponse('{"ret": "true","status": "success", "msg": "注册成功"}', content_type='application/json')
        else:
            return HttpResponse('{"ret": "true","status": "fail", "msg": '+register_form+'}', content_type='application/json')


class getCanView(LoginRequiredMixin, View):
    # 获取用户全部罐头
    def get(self, request):
        if not request.user:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        secretModels = secret.objects.filter(onceName__user__id=int(request.user.id), show=True)
        month = []
        secretUl = []
        # 循环所有秘密
        # 判断是否为8月 yes
        # 把8月份的秘密放到一个数组 X
        for secretLi in secretModels:
            agreeUl = agree.objects.filter(secret__id=secretLi.id, show=True)  # 获取秘密全部点赞
            commentUl = comment.objects.filter(secret__id=secretLi.id, show=True)  # 获取秘密全部评论
            try:
                agreeUser = agree.objects.get(user__id=request.user.id, secret__id=int(secretLi.id),
                                              show=True)  # 获取当前用户是否给当前秘密点赞
            except agree.DoesNotExist:
                agreeUser = 0
            else:
                agreeUser = 1

            if secretLi.topicofc == None:
                word = ""
                wordId = ""
            else:
                topicofcLi = secretLi.topicofc
                word = topicofcLi.content
                wordId = topicofcLi.id

            if len(month) == 0:
                month.append({
                    "Month": int(secretLi.time.month),
                    "Secret": [{
                            "name": secretLi.title,
                            "selectId": secretLi.id,
                            "treeHoleId": secretLi.treeHole.id,
                            "userName": secretLi.onceName.name,
                            "word": word,
                            "wordId": wordId,
                            "content": secretLi.content,
                            "liveNum": len(agreeUl),
                            "userLive": agreeUser,
                            "commentNum": len(commentUl),
                            "dataTime": str(secretLi.time)
                        }]
                })
                continue

            for monthLi in month:
                if monthLi["Month"] == int(secretLi.time.month):
                    monthLi["Secret"].append({
                            "name": secretLi.title,
                            "selectId": secretLi.id,
                            "treeHoleId": secretLi.treeHole.id,
                            "userName": secretLi.onceName.name,
                            "word": word,
                            "wordId": wordId,
                            "content": secretLi.content,
                            "liveNum": len(agreeUl),
                            "userLive": agreeUser,
                            "commentNum": len(commentUl),
                            "dataTime": str(secretLi.time)
                        })
                else:
                    monthExistence = False
                    for monthLi in month:
                        if monthLi["Month"] == int(secretLi.time.month):
                            monthExistence = True
                    if monthExistence == False:
                        month.append({
                            "Month": int(secretLi.time.month),
                            "Secret": []
                        })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": month
        }
        return HttpResponse(json.dumps(resjson), content_type='application/json')


class UserInfoView(LoginRequiredMixin, View):
    # 用户信息获取
    def get(self, request):
        if not request.user:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        UserProfileModels = UserProfile.objects.get(id=int(request.user.id))
        onceNameModels = onceName.objects.filter(user__id=int(request.user.id), current=True, show=True)
        print('xxxxxxxxxxxxxxxxxxxxxxxx')
        try:
            name = onceNameModels[0].name
        except:
            name = '未设置'

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "name": name,
                "years": UserProfileModels.years,
                "sex": UserProfileModels.sex
            }
        }
        return HttpResponse(json.dumps(resjson), content_type='application/json')


class setNameView(LoginRequiredMixin, View):
    # 用户昵称修改
    def get(self, request):
        if not request.user:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        setName_form = setNameForm(request.GET)
        if setName_form.is_valid():
            name = request.GET.get('name', '')
            onceNameModels = onceName.objects.filter(user__id=int(request.user.id), current=True, show=True)

            for onceNameLi in onceNameModels:
                onceNameLi.current = False
                onceNameLi.save()

            onceNameSave = onceName()
            onceNameSave.user = request.user
            onceNameSave.name = name
            onceNameSave.current = True
            onceNameSave.save()

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
